package com.yeskery.nut.web.demo.controller;

import com.yeskery.nut.annotation.bean.Autowired;
import com.yeskery.nut.annotation.web.*;
import com.yeskery.nut.core.Request;
import com.yeskery.nut.core.Response;
import com.yeskery.nut.util.StringUtils;
import com.yeskery.nut.web.demo.biz.OAuthBiz;
import com.yeskery.nut.web.demo.common.R;
import com.yeskery.nut.web.demo.common.UserContext;

/**
 * OAuthController
 * @author YESKERY
 * 2024/11/4
 */
@Controller
@RequestMapping("/oauth")
public class OAuthController {

    @Autowired
    private OAuthBiz oAuthBiz;

    @GetMapping("/login")
    public String authorizePage() {
        return "oauth_authorize";
    }

    @PostMapping("/login")
    public void authorize(Request request, Response response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        if (oAuthBiz.validUser(username, password)) {
            response.sendRedirect(request.getParameter("redirect_uri") + "?code=" + oAuthBiz.getAuthorizationCode(username));
        } else {
            response.writeJsonFromObject(R.fail("用户名或密码错误"));
        }
    }

    @GetMapping("/loginUser")
    @ResponseBody
    public R<String> loginUserName() {
        String userName = UserContext.getOAuthUserName();
        return StringUtils.isEmpty(userName) ? R.fail("Not Login") : R.ok(userName);
    }
}
